package com.i8office.android.zhihuixinwu.ui;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cyan.tools.annotation.ActivityFragmentInject;
import com.cyan.tools.base.BaseActivity;
import com.cyan.tools.util.RxBus;
import com.example.menhoo.toollibrary.common.assist.IMEHelper;
import com.flyco.tablayout.SegmentTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.flyco.tablayout.widget.MsgView;
import com.gyf.barlibrary.ImmersionBar;
import com.i8office.android.zhihuixinwu.R;
import com.i8office.android.zhihuixinwu.bean.TabItem;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;


@ActivityFragmentInject(
        contentViewId = R.layout.activity_office
)
public class OfficeActivity extends BaseActivity implements TextView.OnEditorActionListener {
    @BindView(R.id.tabLayout)
    SegmentTabLayout tabLayout;
    @BindView(R.id.viewpager)
    ViewPager viewpager;
    @BindView(R.id.keyword)
    EditText keyword;
    String titles[] = {"待办","提醒", "已办","收藏"};
    private List<OfficeFragment> fragments = new ArrayList<>();
    private Observable<Integer> observable;
    private Disposable disposable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        ImmersionBar.with(this)
                .statusBarDarkFont(true, 0.2f) //原理：如果当前设备支持状态栏字体变色，会设置状态栏字体为黑色，如果当前设备不支持状态栏字体变色，会使当前状态栏加上透明度，否则不执行透明度
                .init();
        viewpager.setOffscreenPageLimit(3);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        OfficeFragment fragment1 = new OfficeFragment();
        Bundle bundle1 = new Bundle();
        bundle1.putBoolean("is_pending", true);
        fragment1.setArguments(bundle1);
        fragments.add(fragment1);

        OfficeFragment fragment3 = new OfficeFragment();
        Bundle bundle3 = new Bundle();
        bundle3.putBoolean("isNotify", true);
        fragment3.setArguments(bundle3);
        fragments.add(fragment3);

        OfficeFragment fragment2 = new OfficeFragment();
        Bundle bundle2 = new Bundle();
        bundle2.putBoolean("is_pending", false);
        fragment2.setArguments(bundle2);
        fragments.add(fragment2);

        OfficeFragment fragment4 = new OfficeFragment();
        Bundle bundle4 = new Bundle();
        bundle4.putBoolean("is_collect", true);
        fragment4.setArguments(bundle4);
        fragments.add(fragment4);
        keyword.setOnEditorActionListener(this);
        initViewPager();

        observable = RxBus.get().register("OnGetMsgNum", Integer.class);
        disposable = observable.subscribe(new Consumer<Integer>() {
            @Override
            public void accept(final Integer num) throws Exception {
                MsgView msgView = tabLayout.getMsgView(2);
//                tabLayout.showMsg(2, 20);
//                tabLayout.setMsgMargin(2,-5,5);
                msgView.setTextSize(10);
                if (num > 0) {
                    tabLayout.showMsg(1, num);
                } else {
                    tabLayout.hideMsg(1);
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (disposable != null && !disposable.isDisposed()) disposable.dispose();
        if (observable != null) RxBus.get().unregister("OnGetMsgNum", observable);
    }

    //获取Tab
    private void initViewPager() {
        tabLayout.setTabData(titles);
        tabLayout.setVisibility(View.VISIBLE);
        ArrayList<TabItem> tabItems = new ArrayList<TabItem>();
        tabItems.add(new TabItem("1"));
        tabItems.add(new TabItem("2"));
        tabItems.add(new TabItem("3"));
        viewpager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return titles[position];
            }

            @Override
            public int getCount() {
                return titles.length;
            }
        });
        setupWithViewPager();
    }

    private void setupWithViewPager() {
        tabLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        tabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                viewpager.setCurrentItem(position);
                fragments.get(position).refresh();
            }

            @Override
            public void onTabReselect(int position) {
                fragments.get(position).refresh();
            }
        });

        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tabLayout.setCurrentTab(position);
                String keywordStr = fragments.get(viewpager.getCurrentItem()).getKeyword();
                if (!TextUtils.isEmpty(keywordStr)) {
                    keyword.setText(keywordStr);
                    keyword.setSelection(keywordStr.length());
                } else {
                    keyword.setText("");
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }


    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            IMEHelper.hideIME(this, true);
            String keywordStr = keyword.getText().toString().trim();
            fragments.get(viewpager.getCurrentItem()).query(keywordStr);
            return true;
        }
        return false;
    }
}
